package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.amap.api.location.AMapLocation;
import com.github.gcacace.signaturepad.views.SignaturePad;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.ImageTools;
import com.isunland.managesystem.common.SimpleReturnResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.rDistributionMain;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LocationUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.PictureUtil;
import com.isunland.managesystem.utils.SimpleUploadHandler;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.io.File;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/7/20 13:28
 */
public class SignReceiveFragment extends BaseFragment {
  @BindView(R.id.tv_location_attendanceDetail) TextView tvLocation;
  @BindView(R.id.iv_picture_attendanceDetail) ImageView ivPicture;
  @BindView(R.id.ib_photo_attendanceDetail) ImageButton ibTakePhoto;
  //@BindView(R.id.signature_pad_description) TextView signaturePadDescription;
  @BindView(R.id.signature_pad) SignaturePad spSign;
  //@BindView(R.id.signature_pad_container) RelativeLayout signaturePadContainer;
  @BindView(R.id.bt_sign_in) Button btnSign;
  @BindView(R.id.slv_signPerson) SingleLineView slvSignPerson;
  @BindView(R.id.iv_sign) ImageView ivSign;
  @BindView(R.id.slv_signTime) SingleLineView slvSignTime;
  private rDistributionMain mItem;
  private File mCameraFile;
  /** 是否签名 */
  private boolean hasSign;

  public static void newInstance(Fragment fragment, rDistributionMain itemObj) {
    BaseParams<rDistributionMain> params = new BaseParams<>();
    params.setItem(itemObj);
    params.setType(
        MyStringUtil.equalsIgnoreCase(itemObj.getDataStatus(), rDistributionMain.CHECK_PASS)
            ? BaseParams.TYPE_DETAIL : BaseParams.TYPE_EDIT);

    BaseVolleyActivity.newInstance(fragment, SignReceiveActivity.class, params,
        DeliveryListFragment.REQUEST_UPDATE);
  }

  @Override public void initData() {
    super.initData();
    mItem = mBaseParams.getItem() instanceof rDistributionMain
        ? (rDistributionMain) mBaseParams.getItem() : new rDistributionMain();
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_sign_reveive, container, false);
    ButterKnife.bind(this, view);
    return view;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(BaseParams.TYPE_DETAIL == mBaseParams.getType() ? R.string.hasSignReceive
        : R.string.signReceive);
    //数据适配
    btnSign.setText((BaseParams.TYPE_DETAIL == mBaseParams.getType() ? R.string.hasSignReceive
        : R.string.signReceive));
    tvLocation.setText(mItem.getSignLocaltion());
    slvSignPerson.setTextContent(mItem.getSignStaffName());
    slvSignTime.setTextContent(mItem.getSignTime());
    PictureUtil.loadImage(mItem.getSignPhoto(), ivPicture);
    PictureUtil.loadImage(mItem.getSignAutograph(), ivSign);
    //控件禁用
    ivSign.setVisibility(MyStringUtil.isEmpty(mItem.getSignAutograph()) ? View.GONE : View.VISIBLE);
    ivPicture.setVisibility(MyStringUtil.isEmpty(mItem.getSignPhoto()) ? View.GONE : View.VISIBLE);
    slvSignTime.setVisibility(
        mBaseParams.getType() == BaseParams.TYPE_DETAIL ? View.VISIBLE : View.GONE);
    if (BaseParams.TYPE_DETAIL == mBaseParams.getType()) {
      tvLocation.setEnabled(false);
      slvSignPerson.setInputEnabled(false);
      ibTakePhoto.setVisibility(View.GONE);
      spSign.setVisibility(View.GONE);
      btnSign.setEnabled(false);
    }
    //绑定事件.
    LocationUtil.newInstance(mActivity)
        .setSimpleLocationListener(new LocationUtil.SimpleCustomLocationListener() {
          @Override public void onLocationValid(AMapLocation location) {
            mItem.setLatitude(MyStringUtil.valueOf(location.getLatitude()));
            mItem.setLongitude(MyStringUtil.valueOf(location.getLongitude()));
            mItem.setSignLocaltion(location.getAddress());
            tvLocation.setText(location.getAddress());
          }

          @Override public void onLocationError() {
            tvLocation.setText(R.string.noLocation);
          }
        })
        .startLocation();

    ibTakePhoto.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        mCameraFile = PictureUtil.takePhoto(SignReceiveFragment.this, mActivity);
      }
    });
    btnSign.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        sign();
      }
    });
    spSign.setOnSignedListener(new SignaturePad.OnSignedListener() {
      @Override public void onStartSigning() {

      }

      @Override public void onSigned() {
        hasSign = true;
      }

      @Override public void onClear() {

      }
    });
  }

  private void sign() {
    if (slvSignPerson.isEmptyContent()) {
      ToastUtil.show(R.string.notComplete);
      return;
    }
    MyUtils.showDialogLoading(mActivity, getString(R.string.loadingSignReceive));
    if ((mCameraFile != null)
        && (ivPicture.getVisibility() == View.VISIBLE)
        && (MyStringUtil.isEmpty(mItem.getSignPhoto()))) {
      //未上传.路径为空.
      volleyPostUploadPhoto();
    } else if (hasSign && (MyStringUtil.isEmpty(mItem.getSignAutograph()))) {
      volleyPostUploadSignImage();
    } else {
      volleyPostSign();
    }
  }

  private void volleyPostUploadPhoto() {
    new FileNetWorkUtil(getActivity()).upLoadFile(mCameraFile.getAbsolutePath(),
        ApiConst.URL_UPLOAD_FILE, "imsmm.r_distribution_main", mItem.getId(),
        new SimpleUploadHandler() {
          @Override public void onUploadSuccess(@SuppressWarnings("UnusedParameters") String path) {
            super.onUploadSuccess(path);
            mItem.setSignPhoto(path);
            mItem.setSignPhotoName(FileUtil.getFileNameByFilePath(path));
            volleyPostUploadSignImage();
          }
        }, false);
  }

  private void volleyPostUploadSignImage() {
    File file = ImageTools.savePhotoToSDCard(spSign.getSignatureBitmap(), FileUtil.getFileDir(),
        MyStringUtil.valueOf(System.currentTimeMillis()));
    if (file == null) return;
    new FileNetWorkUtil(getActivity()).upLoadFile(file.getAbsolutePath(), ApiConst.URL_UPLOAD_FILE,
        "imsmm.r_distribution_main", mItem.getId(), new SimpleUploadHandler() {
          @Override public void onUploadSuccess(@SuppressWarnings("UnusedParameters") String path) {
            super.onUploadSuccess(path);
            mItem.setSignAutograph(path);
            mItem.setSignAutographName(FileUtil.getFileNameByFilePath(path));
            volleyPostSign();
          }
        }, false);
  }

  private void volleyPostSign() {
    mItem.setSignStaffName(slvSignPerson.getTextContent());

    MyUtils.showDialogLoading(mActivity);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_SIGN_REVIEVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.putAll(mItem);
    mActivity.volleyPost(url, params.getParams(), new SimpleReturnResponse(mActivity));
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == PictureUtil.REQUEST_CAMERA) {
      Bitmap bitmap = PictureUtil.getBitmap(mCameraFile);
      ivPicture.setImageBitmap(bitmap);
      ivPicture.setVisibility(bitmap == null ? View.GONE : View.VISIBLE);
    }
  }
}
